package com.liyiruo.uploadfiles.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author liyiruo
 * @Description
 * @Date 2024/7/22 上午10:29
 */
@RestController
@RequestMapping("upload")
@Slf4j
public class FileServerController {
    private static final String UPLOAD_DIR = "files";
    @RequestMapping("/serverFile")
    @ResponseBody
    public String uploadFiles(@RequestParam("file") MultipartFile[] files,
                              @RequestParam("fileName") String fileName,
                              RedirectAttributes redirectAttributes) {
        log.info("======>{}", fileName);
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue; // 跳过空文件
            }
            try {
                byte[] bytes = file.getBytes();
                Path path = Paths.get(UPLOAD_DIR + File.separator + fileName);
                //如果文件不存在，应该先创建
                Path parentDir = path.getParent();
                // 检查父目录是否存在，如果不存在，则创建它
                if (parentDir != null && !Files.exists(parentDir)) {
                    try {
                        // 创建目录，包括所有必需的父目录
                        Files.createDirectories(parentDir);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                Files.write(path, bytes);
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败的文件: " + fileName;
            }
        }
        return "上传成功的文件: " + fileName;
    }
}
